const Koa = require("koa")
const koaBody = require("koa-body")
const koaStatic = require("koa-static-cache")
const koaViews = require("koa-views")
const session = require('koa-session')
const { sessionSecret, staticConfig } = require("./config")

// 引入路由
const router = require("./router")
const routerGoodsPage = require("./router/pages/goods")
const routerUserApi = require("./router/apis/user")
const { getAllCategory } = require('./service/category')

// 创建实例
const app = new Koa()
app.keys = [sessionSecret.key]  // 加密规则 ，不要泄露给其他人
// 配置中间件
app.use(koaStatic(staticConfig))
app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: "./public/uploads",
    keepExtensions: true,
    maxFileSize: "2mb"
  }
}))
app.use(koaViews(__dirname + "/views", {
  map: {
    "html": "nunjucks"
  }
}))
app.use(session(sessionSecret.config, app))

// 配置全局变量
app.use(async (ctx, next) => {
  // koa 提供了 state 对象 ，用于通过中间件传递信息到前端视图，所有前端视图都可以直接使用信息
  ctx.state.categories = await getAllCategory()
  if (ctx.session.user) {
    ctx.state.user = ctx.session.user
  }
  await next()
})

// 注册路由
app.use(router.routes())
app.use(routerGoodsPage.routes())
app.use(routerUserApi.routes())

// 监听
app.listen(8090, () => {
  console.log("run on port 8090")
})
